<template>
  <el-form ref="refForm" :model="model.form"
    label-width="220px"
    autocomplete="off">
    <el-form-item v-for="(item, index) in model.form" :label="item.title">
      <el-input v-if="item.type==='text'" v-model.trim="item.value" :placeholder="item.title"/>

      <div v-if="item.type === 'file'">
        <el-upload class="upload-demo" ref="refUpload"
          accept="pem"
          :action="uploadServer+'?original='+item.name"
          :headers="{ Authorization: local.get('ADMIN.TOKEN') || '' }"
          :before-upload="(file) => uploadBefore(file, index)"
          :on-success="(response, file) => uploadSuccess(response, file, index)"
          :on-error="uploadError"
          :show-file-list="false">
          <div v-if="item.value" style="color: var(--el-color-primary)">{{ item.value }}</div>
          <el-icon v-else class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <template #tip>
            <div class="el-upload__tip" v-html="item.tips"></div>
          </template>
        </el-upload>
      </div>
    </el-form-item>
    <el-button v-if="dev" type="primary" @click="submit">保存</el-button>
  </el-form>
</template>

<script setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from "vue";
import { local } from "../../utils/storage";
import { ElMessage } from "element-plus";
import { AdminConfigGet, AdminConfigPost } from "../../api/server/config";
import { uploadServer } from "../../utils";
import router from "../../router";


const refForm = ref(null)
const dev = ref(false)
const model = reactive({
  form: null
})

onMounted(() => {
  const { query } = router.currentRoute.value
  dev.value = query.dev === 'true'
  getConfigInfo()
})

const getConfigInfo = () => {
  AdminConfigGet({ group: 'wechat_pem' }).then(({ data: { info } }) => {
    model.form = info
  })
}

const submit = () => {
  AdminConfigPost(model.form).then(() => {
    ElMessage.success('配置信息已更新')
  })
}

const uploadBefore = (file, index) => {
  model.form[index].name = file.name
}

// 文件上传成功回调
const uploadSuccess = (response, file, index) => {
  if (response.code === 200) {
    model.form[index].value = response.data
  } else {
    ElMessage.error('Upload failed: ' + response.msg)
  }
}
// 文件上传失败回调
const uploadError = (e, file) => {
  ElMessage.error('Upload failed: ' + e.msg)
}
</script>

<style scoped>
.container {
  padding: 0 20px;
}

.header span {
  color: rgb(82, 171, 173);
}

.el-button--primary {
  margin-left: 180px;
}

.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  border-radius: 10px;
  border: 1px solid var(--el-border-color-light);
  font-size: 36px;
  color: var(--el-color-info-light-5);
}
</style>
